package com.gwt.dispatcher.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.gwt.dispatcher.dispatcher.client.Dispatcher;
import com.gwt.dispatcher.shared.IncrementCounterAction;
import com.gwt.dispatcher.shared.IncrementCounterResult;

public class CustomDispatcher implements EntryPoint {

HorizontalPanel main = new HorizontalPanel();
  
  private Integer prop = 0;
  
  public void onModuleLoad() {
    
    main.setSpacing(10);
    
    Label label = new Label("Click 'Ok' to increment the counter");
    final Label result = new Label();
    Button button = new Button("Ok");
    button.addClickHandler(new ClickHandler(){
      public void onClick(ClickEvent event) {
        Dispatcher.execute( new IncrementCounterAction( 10 ), new AsyncCallback<IncrementCounterResult>() {
                public void onFailure( Throwable e ) {
                    Window.alert( "Error: " + e.getMessage() );
                }
                public void onSuccess( IncrementCounterResult result ) {
                    Window.alert( "Incremented by " + result.getAmount() + ", new total is " + result.getCurrent() );
                    prop = result.getCurrent();
                }
            });
      }
    });
    
    result.addClickHandler(new ClickHandler(){

      public void onClick(ClickEvent event) {
        
        Dispatcher.execute( new IncrementCounterAction( prop ), new AsyncCallback<IncrementCounterResult>() {
                public void onFailure( Throwable e ) {
                    Window.alert( "Error: " + e.getMessage() );
                }
                public void onSuccess( IncrementCounterResult result ) {
                    Window.alert( "Incremented by " + result.getAmount() + ", new total is " + result.getCurrent() );
                }
            });
        
      }
      
    });
    
    main.add(label);
    main.add(button);
    main.add(result);
    
    RootPanel.get("mainContainer").add(main);
    
  }
}
